package com.leyou.cart.service;

import com.leyou.cart.intercept.LoginIntercept;
import com.leyou.cart.pojo.Cart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Stream;

/**
 * 项目: leyou
 *
 * @author 岩冰
 * @version 2018/10/20 11:23
 */
@Service
public class CartService {
    @Autowired
    private RedisTemplate redisTemplate;

    static final String KEY_PREFIX = "ly:cart:uid:";

    static final Logger logger = LoggerFactory.getLogger(CartService.class);
    public List<Cart> queryCarts() {

        String key = KEY_PREFIX + LoginIntercept.geUserInfo().getId();
        List<Cart> carts = this.redisTemplate.boundHashOps(key).values();
        return carts;
    }


    public void addCart(Cart cart) {
        String key = KEY_PREFIX + LoginIntercept.geUserInfo().getId();
        //判断是否含有key
        BoundHashOperations ops = redisTemplate.boundHashOps(key);
        String hKey = cart.getSkuId().toString();
        if (ops.hasKey(hKey)) {
            Cart cart1 = (Cart) ops.get(hKey);
            cart1.setNum(cart1.getNum() + cart.getNum());
            ops.put(hKey, cart1);
        } else {
            //没有的话直接天际撒
            ops.put(hKey, cart);
        }
    }

    /**
     * 合并cart
     * @param carts
     */
    public void combineCarts(Cart[] carts) {
        Stream.of(carts).forEach(this::addCart);
    }


    /**
     * 修改数量.逻辑在添加中已经写过了
     * @param skuId
     * @param num
     */
    public void updateCarts(Long skuId, Integer num) {
        Cart cart = new Cart();
        cart.setSkuId(skuId);
        cart.setNum(num);
        this.addCart(cart);
    }

    /**
     * 根据sku的id删除sku的仓库
     * @param id
     */
    public void deleteCarts(String id) {
        String key = KEY_PREFIX + LoginIntercept.geUserInfo().getId();
        //判断是否含有key
        BoundHashOperations ops = redisTemplate.boundHashOps(key);
        ops.delete(id);
    }
}
